#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import wx
import wx.grid
import xmmsclient.glib
import gobject
import ConfigParser
import taskbaricon

class X2T(wx.Frame):
	def __init__(self, *args, **kwds):
		kwds["style"] = wx.ICONIZE|wx.CAPTION|wx.SYSTEM_MENU|wx.FRAME_FLOAT_ON_PARENT|wx.CLIP_CHILDREN|wx.MINIMIZE_BOX|wx.FRAME_NO_TASKBAR
		wx.Frame.__init__(self, *args, **kwds)
		self.TrayIcon = taskbaricon.icon(self, wx.Icon("data/icon.png", wx.BITMAP_TYPE_PNG),"XMMS2 & Twitter")
		
		self.cfg = ConfigParser.ConfigParser()
		self.core = None
		
		self.__read_config()
		self.__load_objects()
		self.__set_properties()
		self.__do_layout()
		self.__set_actions()
		
	def setCore(self, core):
		self.core = core
		
		self.ml = gobject.MainLoop(None, False)
		conn = xmmsclient.glib.GLibConnector(self.core)
		
		self.__set_Status()
		
		self.core.playback_current_id(self.core.onChange)
		self.core.broadcast_playback_current_id(self.core.onChange)
		
	def __load_objects(self):
		self.notebook_1 = wx.Notebook(self, -1, style=0)
		self.tabConection = wx.Panel(self.notebook_1, -1)
		self.tabAbout = wx.Panel(self.notebook_1, -1)
		self.FrameXT_statusbar = self.CreateStatusBar(2, 0)
		self.bitmap_1 = wx.StaticBitmap(self.tabAbout, -1, wx.Bitmap("data/xt.png", wx.BITMAP_TYPE_ANY))
		self.label_2 = wx.StaticText(self.tabAbout, -1, "X2T is a simple app by send messages \nof played songs from XMMS2 to Twitter", style=wx.ALIGN_CENTRE)
		self.panel_6 = wx.Panel(self.tabAbout, -1)
		self.imageTwitter = wx.StaticBitmap(self.tabConection, -1, wx.Bitmap("data/twitter.png", wx.BITMAP_TYPE_ANY))
		self.panel_2 = wx.Panel(self.tabConection, -1)
		self.lbUsername = wx.StaticText(self.tabConection, -1, "Username:")
		self.txtUsername = wx.TextCtrl(self.tabConection, -1, "")
		self.lbPassword = wx.StaticText(self.tabConection, -1, "Password:")
		self.txtPassword = wx.TextCtrl(self.tabConection, -1, "", style=wx.TE_PASSWORD)
		self.btConnect = wx.Button(self.tabConection, -1, "Connect")
		self.panel_4 = wx.Panel(self.tabConection, -1)
		self.parametersGrid = wx.grid.Grid(self.notebook_1, -1, size=(1, 1))
        
	def __set_properties(self):
		self.SetTitle("XMMS2 & Twitter")
		self.SetToolTipString("XMMS2 & Twitter")
		self.panel_2.SetMinSize((110, 20))
		self.lbUsername.SetMinSize((68, 14))
		self.txtUsername.SetMinSize((90, 20))
		self.lbPassword.SetMinSize((100, 14))
		self.txtPassword.SetMinSize((90, 20))
		self.panel_4.SetMinSize((110, 20))
		self.parametersGrid.CreateGrid(10, 2)
		self.parametersGrid.SetColLabelValue(0, "Parameter")
		self.parametersGrid.SetColSize(0, 80)
		self.parametersGrid.SetColLabelValue(1, "Value")
		self.FrameXT_statusbar.SetStatusWidths([-1, -1])
		self.parametersGrid.SetColSize(1, 200)		
		
		#load parameters
		if self.cfg.has_section("parameters"):
			options = self.cfg.options("parameters")
			for i in range(len(options)):
				self.parametersGrid.SetCellValue(i,0,options[i])
				self.parametersGrid.SetCellValue(i,1,self.cfg.get("parameters",options[i]))
		
		#load session
		if self.cfg.has_option("login","username"):
			self.txtUsername.SetValue(self.cfg.get("login","username"))
			self.txtPassword.SetValue(self.cfg.get("login","password"))

		
	def __do_layout(self):
		sizer_1 = wx.BoxSizer(wx.VERTICAL)
		sizer_2 = wx.BoxSizer(wx.HORIZONTAL)
		sizer_3 = wx.BoxSizer(wx.VERTICAL)
		sizer_4 = wx.BoxSizer(wx.HORIZONTAL)
		sizer_5 = wx.BoxSizer(wx.VERTICAL)
		sizer_5.Add(self.bitmap_1, 0, wx.TOP|wx.ALIGN_CENTER_HORIZONTAL|wx.ADJUST_MINSIZE, 30)
		sizer_5.Add(self.label_2, 0, wx.EXPAND|wx.ADJUST_MINSIZE, 0)
		sizer_5.Add(self.panel_6, 1, wx.EXPAND, 0)
		sizer_4.Add(sizer_5, 1, wx.EXPAND, 0)
		self.tabAbout.SetSizer(sizer_4)
		sizer_2.Add(self.imageTwitter, 0, wx.TOP|wx.ADJUST_MINSIZE, 5)
		sizer_3.Add(self.panel_2, 1, 0, 0)
		sizer_3.Add(self.lbUsername, 0, wx.ALIGN_BOTTOM|wx.ADJUST_MINSIZE, 0)
		sizer_3.Add(self.txtUsername, 0, wx.BOTTOM|wx.ADJUST_MINSIZE, 5)
		sizer_3.Add(self.lbPassword, 0, wx.ALIGN_BOTTOM|wx.ADJUST_MINSIZE, 0)
		sizer_3.Add(self.txtPassword, 0, wx.BOTTOM|wx.ADJUST_MINSIZE, 5)
		sizer_3.Add(self.btConnect, 0, wx.ADJUST_MINSIZE, 0)
		sizer_3.Add(self.panel_4, 1, 0, 0)
		sizer_2.Add(sizer_3, 1, wx.EXPAND, 1)
		self.tabConection.SetSizer(sizer_2)
		self.notebook_1.AddPage(self.tabAbout, "About")
		self.notebook_1.AddPage(self.tabConection, "Connection")
		self.notebook_1.AddPage(self.parametersGrid, "Preferences")
		sizer_1.Add(self.notebook_1, 1, wx.EXPAND, 0)
		self.SetSizer(sizer_1)
		sizer_1.Fit(self)
		self.Layout()
		self.Centre()

	def __set_actions(self):
		self.Bind(wx.grid.EVT_GRID_CELL_CHANGE, self.handler_keydown_parametersGrid, self.parametersGrid)
		self.Bind(wx.EVT_BUTTON, self.handler_connectToTwitter, self.btConnect)
		
	
	def handler_keydown_parametersGrid(self, event):
		option = self.parametersGrid.GetCellValue(event.GetRow(),0)
		value = self.parametersGrid.GetCellValue(event.GetRow(),1)
		if len(option) == 0:
			self.__show_message("Add a first parameter please")
			self.parametersGrid.SetCellValue(event.GetRow(),1,"")
			return
		self.__set_parameter(option, value)

		if option == "filter": self.core.setFilter(value)
		if option == "mode": self.core.setMode(value)
				
		
	def handler_connectToTwitter(self, event):
		if self.btConnect.GetLabel() == "Connect":
			self.__set_option("login","username",self.txtUsername.GetValue())
			self.__set_option("login","password",self.txtPassword.GetValue())
		
			if not self.core.loginTwitter(self.txtUsername.GetValue(),self.txtPassword.GetValue()):
				self.__show_message("The user and the password is incorrect.")
			else: 
				self.__show_message("Success !")
			
			self.__set_Status()
		else:
			self.core.unloginTwitter()
			self.__set_Status()

		
	def __read_config(self):	
		try:
			if not os.path.isdir(os.path.expanduser('~/.x2t')):
				os.mkdir(os.path.expanduser('~/.x2t'))			
			if not os.path.isfile(os.path.expanduser('~/.x2t/config.cfg')):
				self.cfg.add_section("parameters")
				self.cfg.set("parameters", "filter", "Listen %artist - %title from %album album through x2t")
				self.cfg.set("parameters", "active", "0")
				self.cfg.set("parameters", "mode", "0")
				self.cfg.add_section("login")
				self.cfg.set("login", "username", "user")
				self.cfg.set("login", "password", "password")
				self.__write_parameters()
			self.cfg.read(['config.cfg', os.path.expanduser('~/.x2t/config.cfg')])
		except:
			print "Ocurrio algo en __read_config"
	
	def __set_parameter(self, option, value):
		try:
			self.cfg.set("parameters", option, value)
			#self.__write_parameters()
		except:
			print "Ocurrio algo en __set_parameter"

	def __set_option(self, section, option, value):
		try:
			self.cfg.set(section, option, value)
			self.__write_parameters()
		except:
			print "Ocurrio algo en __set_option"
	
	def __write_parameters(self):
		_file = open(os.path.expanduser('~/.x2t/config.cfg'), "w")
		self.cfg.write(_file)
		_file.close()
	
	def __set_Status(self):
		xmms_status = "OFF"
		twitter_status = "OFF"

		if self.core.isConnected(): xmms_status = "ON"
		if self.cfg.has_option("parameters","active") and self.cfg.get("parameters","active") == "1":
			if self.core.isConnectTwitter()==0 and self.core.loginTwitter(self.txtUsername.GetValue(),self.txtPassword.GetValue()): 
				twitter_status = "ON"

		if self.core.isConnectTwitter()==1:
			self.txtUsername.SetEditable(False)
			self.txtPassword.SetEditable(False)
			self.btConnect.SetLabel("Disconnect")
			twitter_status = "ON"
		else:
			self.txtUsername.SetEditable(True)
			self.txtPassword.SetEditable(True)
			self.btConnect.SetLabel("Connect")
				
		FrameXT_statusbar_fields = ["XMMS2 status: " + xmms_status, "Connection Twitter: " + twitter_status]
		for i in range(len(FrameXT_statusbar_fields)):
			self.FrameXT_statusbar.SetStatusText(FrameXT_statusbar_fields[i], i)
		
		if self.cfg.has_option("parameters","filter"): self.core.setFilter(self.cfg.get("parameters","filter"))
		if self.cfg.has_option("parameters","mode"): self.core.setMode(self.cfg.get("parameters","mode"))
		
	def __show_message(self, message):
		dlg = wx.MessageDialog(self, message,'x2t',wx.OK | wx.ICON_INFORMATION)
		dlg.ShowModal()
		dlg.Destroy()
		
	def __del__(self):
		self.__write_parameters()
		self.ml.quit()
		
	def print_configfile(self):
		secciones = self.cfg.sections()
		for sec in secciones:
			print sec
			opciones = self.cfg.options(sec)
			for op in opciones:
				print "\t",op,self.cfg.get(sec,op)
